/*
 * @Author: 陈德基
 * @Date: 2021-11-15 18:47:10
 * @LastEditTime: 2021-11-16 22:54:08
 * @Description: 
 * @FilePath: \copy_gsy_github_app_flutter\lib\repository\dynamic_repository.dart
 * 联系方式：
 * wx: melody_2009
 * qq: 7815171323 
 */

import 'dart:convert';

import 'package:copy_gsy_github_app_flutter/common/model/Event.dart';
import 'package:copy_gsy_github_app_flutter/common/net/address.dart';
import 'package:copy_gsy_github_app_flutter/common/net/api.dart';
import 'package:copy_gsy_github_app_flutter/db/provider/dynamic/dynamic_db_provider.dart';
import 'package:copy_gsy_github_app_flutter/repository/dao_result.dart';

/// 用于处理用户动态数据层的业务
class DynamicRepository {
  static getDynamicList(String? name, {page = 1, bool needDb = false}) async {
    if (name == null) {
      return null;
    }

    DynamicDbProvider provider = DynamicDbProvider();
    request() async {
      String url =
          Address.getEventReceived(name) + Address.getPageParams('?', page);
      var res = await httpManager.netFetch(url, null, null, null);
      if (res != null && res.result) {
        List<Event> list = [];
        var data = res.data;
        if (data == null || data.length == 0) {
          return DataResult(null, false);
        }
        if (needDb) {
          // 先将数据插入到数据库
          await provider.insert(json.encode(data));
        }
        for (int i = 0; i < data.length; i++) {
          list.add(Event.fromJson(data[i]));
        }
        return DataResult(list, true);
      } else {
        return DataResult(null, false);
      }
    }

    if (needDb) {
      List<Event>? dbList = await provider.getDynamic();
      if (dbList == null || dbList.length == 0) {
        return await request();
      }
      DataResult dataResult = DataResult(dbList, true, next: request);
      return dataResult;
    }
    return await request();
  }
}
